package com.campus.dao.impl;

import com.campus.dao.ClassDao;
import com.campus.model.Class;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @desc: 教学班数据访问对象实现类
 * @author: hjm
 * @date: 2024/11/22
 */
@Repository
@Slf4j
public class ClassDaoImpl implements ClassDao {

    private final JdbcTemplate jdbcTemplate;

    // 构造函数注入JdbcTemplate
    public ClassDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 创建教学班
     * @param cls 教学班对象
     * @return 受影响的行数
     */
    @Override
    public int createClass(Class cls) {
        String sql = "INSERT INTO t_manager_class (name, created_time, class_desc, teacher_id, activity_id) VALUES (?, ?, ?, ?, ?)";
        return jdbcTemplate.update(sql, cls.getName(), cls.getCreatedTime(), cls.getClassDesc(), cls.getTeacherId(), cls.getActivityId());
    }

    /**
     * 更新教学班信息
     * @param cls 教学班对象
     * @return 受影响的行数
     */
    @Override
    public int updateClass(Class cls) {
        String sql = "UPDATE t_manager_class SET name = ?, class_desc = ?, teacher_id = ?, activity_id = ? WHERE id = ?";
        return jdbcTemplate.update(sql, cls.getName(), cls.getClassDesc(), cls.getTeacherId(), cls.getActivityId(), cls.getId());
    }

    /**
     * 向教学班添加学员
     * @param classId 教学班ID
     * @param studentIds 学员ID列表
     * @return 受影响的行数
     */
    @Override
    public int addStudentsToClass(int classId, List<Integer> studentIds) {
        if (studentIds == null || studentIds.isEmpty()) {
            return 0;
        }

        String sql = "INSERT INTO t_teaching_student_in_class (class_id, student_id) VALUES (?, ?)";
        int rowsAffected = 0;
        try {
            for (Integer studentId : studentIds) {
                rowsAffected += jdbcTemplate.update(sql, classId, studentId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return rowsAffected;
    }

    /**
     * 为教学班分配教师
     * @param classId 教学班ID
     * @param teacherIds 教师ID列表
     * @return 受影响的行数
     */
    @Override
    public int assignTeachersToClass(int classId, List<Integer> teacherIds) {
        String sql = "INSERT INTO t_manager_class_teacher (class_id, teacher_id) VALUES (?, ?)";
        int rowsAffected = 0;
        for (Integer teacherId : teacherIds) {
            rowsAffected += jdbcTemplate.update(sql, classId, teacherId);
        }
        return rowsAffected;
    }
}